<?php

namespace catchAdmin\customs\controller;

use catcher\CatchResponse;
use think\Response;
use think\facade\Db;
use catcher\Code;
use app\Request;
class Customs
{
    public function platDataOpen(Request $request)
    {

        $post_data = $request->post();
        if (!array_key_exists('openReq', $post_data)) {
            return json(['code' => '10001','message'  => '缺少openReq参数',]);
        }
        $params = json_decode(urldecode($post_data['openReq']), true);


        if (count($params) == 3 && array_key_exists('orderNo', $params) && array_key_exists('sessionID', $params) && array_key_exists('serviceTime', $params)) {
            $params['create_time'] = date('Y-m-d H:i:s');
            $result = Db::table('db_customs_get')->insert($params);
            if ($result) {
                return json(['code' => '10000','message'  => '','serviceTime' => time()]);
            } else {
                return json(['code' => '10001','message'  => '存储失败','serviceTime' => time()]);
            }
        } else {
            return json(['code' => '10002','message'  => 'orderNo,sessionID,serviceTime参数缺失','serviceTime' => time()]);
        }
    }
    //轮询签名接口及页面
    public function poll_sign()
    {

        //查出需要回应的第一条订单记录 今日创建的  其他时间没有意义
        $record = Db::table('db_customs_get')
            ->where([
                'status'      => 0
            ])->find();
        if ($record) {
            $sessionID    = $record['sessionID'];
            $payExInfoStr = $this->get_params($sessionID);
            $serviceTime  = time() * 1000;
            $now_date     = date('Y-m-d H:i:s');
            //json_encode不转义中文
            $order_param = '"sessionID":"' . $sessionID . '"||"payExchangeInfoHead":"' . json_encode($payExInfoStr['payExchangeInfoHead'], JSON_UNESCAPED_UNICODE) . '"||"payExchangeInfoLists":"' . json_encode($payExInfoStr['payExchangeInfoLists'], JSON_UNESCAPED_UNICODE) . '"||"serviceTime":"' . $serviceTime . '"';

            $back_data = ['status' => 1, 'order_param' => $order_param, 'pwd' => '88888888', 'serviceTime' => $serviceTime, 'now_date' => $now_date, 'sessionID' => $sessionID];

        } else {
            $back_data = ['status' => 0];
        }
        return json($back_data);
    }

    //
    public function realTimeDataUp(Request $request)
    {
        $params       = $request->post();
        $sessionID    = $params['sessionID'];
        $payExInfoStr = $this->get_params($sessionID);

        $payExInfoStr['serviceTime'] = $params['serviceTime'];
        $payExInfoStr['certNo']      = $params['certNo'];
        // $payExInfoStr['signValue'] = "NkG4m0whKWmB3NPXZfl/dufDDV8cFDoryiJsjrr+CPUrekvjQokNtSIgaEN1fR3L4QKRD2n0ir/WGblclgCKrX5sD05fwSQEZfUh2L66O4CZW/NfULnEt4onNjdVtiXo0bpRiKcMP5qxtQ5hVLoftBtZ2VnZc6aGBrtrIC+WN9w=";
        $payExInfoStr['signValue'] = $params['signValue'];
        $data['payExInfoStr']      = json_encode($payExInfoStr, JSON_UNESCAPED_UNICODE);
        //$url = 'https://swapptest.singlewindow.cn/ceb2grab/grab/realTimeDataUpload';
        $url = 'https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload';
        $result = $this->Curl($url, $data);
        if (is_array($result) && array_key_exists('code', $result)) {
            //重复或成功
            if($result['code'] == '10000' || $result['code'] == '20006'){
                Db::table('db_customs_get')->where(array(
                    'sessionID' => $sessionID,
                ))->save(array('status' => 1, 'modify_time' => date('Y-m-d H:i:s')));

            }
            return json($result);

        } else {
            return json(['code' => '10001','message'  => '上传请求失败']);
        }
    }

    //获取参数
    public function get_params($sessionID)
    {

        //查出需要回应的第一条订单记录 今日创建的  其他时间没有意义
        $c_record = Db::table('db_customs_get')->where(array(
            'status'    => 0,
            'sessionID' => $sessionID,
        ))->find();

        //海关接口订单是多个数组格式
        $orderInfo = Db::table('db_customs_order')->field('orderId,realPayment,orderDate,payOrderNo,payment,paycomCode,ebpCode,ebpName,paymentsub,currency,status')->where(array('orderId' => $c_record['orderNo']))->select();
        //echo M('db_customs_order')->_sql();
        //var_dump($orderInfo);die;
        $orderLists = array();
        foreach ($orderInfo as $key => $value) {

            $orderlistInfo = Db::table('db_customs_orderlist')->field('productName,goods_url')->where(array('orderId' => $value['orderId']))->select();
            $o_infos       = array();
            foreach ($orderlistInfo as $k => $v) {
                $o_info             = array();
                $o_info['gname']    = $v['productName'];
                $o_info['itemLink'] = urlencode($v['goods_url']); //地址要做urlencode处理
                $o_infos[]          = $o_info;
            }
            $orderList                = array();
            $orderList['orderNo']     = $value['orderId'];
            $orderList['goodsInfo']   = $o_infos;
            $orderList['recpAccount'] = $value['orderId']; //收款账号交易商品的卖方商户账号。电商平台自营商户应填写自营商户的收款账户；非自营电商应填写非自营商户的收款账户。
            $orderList['recpCode']    = $value['ebpCode']; //应填写收款企业代码（境内企业为统一社会信用代码；境外企业可不填写）
            $orderList['recpName']    = $value['ebpName']; //应填写收款企业名称
            $orderLists[]             = $orderList;

        }
        $nstr = rand(100000,999999);

        $payExInfoStr['sessionID']           = $sessionID;
        $payExInfoStr['payExchangeInfoHead'] = array(
            "guid"             => '9D55BA71-22DE-41F4-8B50-C36C83B3B530', //企业系统生成36位唯一序号（英文字母大写）
            "initalRequest"    => urlencode($orderInfo[0]['paymentsub']), //跨境电商平台企业向支付企业发送的原始信息
            "initalResponse"   => urlencode($orderInfo[0]['payment']), //支付企业向跨境电商平台企业反馈的原始信息
            "ebpCode"          => $orderInfo[0]['ebpCode'], //电商平台的海关注册登记编号
            "payCode"          => $orderInfo[0]['paycomCode'], //支付企业的海关注册登记编号
            "payTransactionId" => $orderInfo[0]['payOrderNo'], //交易唯一编号（可在央行认可的机构验证）
            "totalAmount"      => floatval($orderInfo[0]['realPayment']), //实际交易金额
            "currency"         => $orderInfo[0]['currency'], //实际交易币制（海关编码）
            "verDept"          => "3", //1-银联 2-网联 3-其他
            "payType"          => "4", //用户支付的类型1-APP 2-PC 3-扫码 4-其他
            "tradingTime"      => date("YmdHis",strtotime($orderInfo[0]['orderDate'])), //交易支付时间
            "note"             => "",
        );
        $payExInfoStr['payExchangeInfoLists'] = $orderLists;
        return $payExInfoStr;

        // $payExInfoStr['sessionID'] = $sessionID;
        // $payExInfoStr['payExchangeInfoHead'] = array(
        //     "guid"=>"9D55BA71-22DE-41F4-8B50-C36C83B3B530",//企业系统生成36位唯一序号（英文字母大写）
        //     "initalRequest"=>urlencode("原始请求"),//跨境电商平台企业向支付企业发送的原始信息
        //     "initalResponse"=>urlencode("原始回调"),//支付企业向跨境电商平台企业反馈的原始信息
        //     "ebpCode"=>"3201968B31",//电商平台的海关注册登记编号
        //     "payCode"=>"110896T012",//支付企业的海关注册登记编号
        //     "payTransactionId"=>"2018121222001354081010726129",//交易唯一编号（可在央行认可的机构验证）
        //     "totalAmount"=>0.01,//实际交易金额
        //     "currency"=>"142",//实际交易币制（海关编码）
        //     "verDept"=>"3",//1-银联 2-网联 3-其他
        //     "payType"=>"4",//用户支付的类型1-APP 2-PC 3-扫码 4-其他
        //     "tradingTime"=>"20181212041803",//交易支付时间
        //     "note"=>"",
        // );
        // $payExInfoStr['payExchangeInfoLists'] = array(
        //     array(
        //         "orderNo"=>"SO1710301150602574003",
        //         "goodsInfo"=>array(
        //             array(
        //                 "gname"=>"小吃1",
        //                 "itemLink"=>urlencode("http://m.yunjiweidian.com/yunjibuyer/static/vue-buyer/idc/index.html#/detail?itemId=999761&shopId=453")
        //             ),
        //             array(
        //                 "gname"=>"小吃2",
        //                 "itemLink"=>urlencode("http://m.yunjiweidian.com/yunjibuyer/static/vue-buyer/idc/index.html#/detail?itemId=999761&shopId=453")
        //             ),
        //         ),
        //         "recpAccount"=>"SO1710301150602574003",//收款账号交易商品的卖方商户账号。电商平台自营商户应填写自营商户的收款账户；非自营电商应填写非自营商户的收款账户。
        //         "recpCode"=>"",//应填写收款企业代码（境内企业为统一社会信用代码；境外企业可不填写）
        //         "recpName"=>"南京龙潭跨境贸易产业服务有限公司",//应填写收款企业名称
        //     ),
        // );
        // return $payExInfoStr;
    }
    public function Curl($url, $data)
    {
        $ch     = curl_init();
        $header = array('Accept-Charset: utf-8');
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $errorno = curl_errno($ch);
        if ($errorno) {
            return $errorno;
        } else {
            $tmpInfo = json_decode($tmpInfo, true);
            return $tmpInfo;
        }
    }
}